<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户查询" prop="userId">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货次数" prop="userId">
        <el-input
          v-model="queryParams.shipments"
          placeholder="请输入发货次数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="激活时间" prop="timeArr">
        <el-date-picker
          v-model="queryParams.timeArr"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:detalis:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detalisList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="状态" align="center" prop="state" >
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0">未激活</span>
          <span v-if="scope.row.state == 1">已激活</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定用户" align="center" prop="nickName" />
      <el-table-column label="激活时间" align="center" prop="creationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货次数" align="center" prop="shipments" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDeliverGoods(scope.row)"
          >发货</el-button>
          <el-button
            size="mini"
            type="text"
            @click="updateAddress(scope.row)"
          >修改收货地址</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改识别码详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="00px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="0未激活 1激活" prop="state">
          <el-input v-model="form.state" placeholder="请输入0未激活 1激活" />
        </el-form-item>
        <el-form-item label="绑定用户" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入绑定用户" />
        </el-form-item>
        <el-form-item label="激活时间" prop="creationTime">
          <el-date-picker clearable
            v-model="form.creationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择激活时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收货人" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收货人" />
        </el-form-item>
        <el-form-item label="收货人电话" prop="consigneePhone">
          <el-input v-model="form.consigneePhone" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item label="地址" prop="consigneeAddress">
          <el-input v-model="form.consigneeAddress" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="区域" prop="region">
          <el-input v-model="form.region" placeholder="请输入区域" />
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-input v-model="form.province" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="form.city" placeholder="请输入市" />
        </el-form-item>
        <el-form-item label="运单号" prop="waybill">
          <el-input v-model="form.waybill" placeholder="请输入运单号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="发货" :visible.sync="openDeliverGoodsOpen" width="500px">
      <div style="margin: 0 0 12px;">联系人：{{detail.consignee}}</div>
      <div style="margin: 12px 0;">联系电话：{{detail.consigneePhone}}</div>
      <div style="margin: 12px 0;">收件地址：{{detail.consigneeAddress}}</div>
      <div style="margin: 12px 0;">商品名称：{{detail.goodsName}}</div>
      <div style="margin: 12px 0;">物流单号：<el-input v-model="waybill" placeholder="请输入订单号" size="small" style="width: 350px"/></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deliverGoods">确认发货</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改收货地址" :visible.sync="changeAddressDialog" width="500px">
      <div style="margin: 12px">
        <div style="display: flex;align-items: center">
          <div style="width: 80px;text-align: right;">省市区：</div>
          <div style="width: calc(100% - 80px)">
            <el-cascader style="width: 100%" v-model="address" :options="options_native_place"/>
          </div>
        </div>
      </div>
      <div style="margin: 12px">
        <div style="display: flex;align-items: center">
          <div style="width: 80px;text-align: right;">详细地址：</div>
          <div style="width: calc(100% - 80px)">
            <el-input v-model="addressText" clearable placeholder="请输入详细地址" size="small"/>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeAddressFun">确认修改</el-button>
        <el-button @click="cancelChange">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  listDetalis,
  getDetalis,
  delDetalis,
  addDetalis,
  updateDetalis,
  listActivatedList, getOrderAddress, changeOrderAddress
} from "@/api/system/codedetail";
import {packageShipping} from "@/api/system/codeid";
import {provinceAndCityData,pcTextArr,regionData,pcaTextArr,codeToText}from "element-china-area-data"

export default {
  name: "CodeDetails",
  data() {
    return {
      address:[],
      addressText:'',
      options_native_place:null,
      changeAddressDialog:false,
      detail:{
        consignee:'',
        consigneePhone:'',
        consigneeAddress:''
      },
      waybill:'',
      openDeliverGoodsOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 识别码详情表格数据
      detalisList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shipments: null,
        nickName: null,
        timeArr: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      addressObject:{}
    };
  },
  created() {
    let list = regionData;
    list.forEach(item=>{
      item.children&&item.children.forEach(item2=>{
        if(item2.label === '市辖区'){
          item2.label = item.label
        }
      })
    })
    this.options_native_place = list;
    this.getList();
  },
  methods: {
    changeAddressFun(){
      let province = this.address[0];
      let city = this.address[1];
      let region = this.address[2];
      let provinceName = codeToText[province];
      let cityName = codeToText[city];
      if(cityName === '市辖区'){
        cityName = provinceName
      }
      let regionName = codeToText[region]
      changeOrderAddress({
        region:regionName,
        consigneeAddress:this.addressText,
        city:cityName,
        province:provinceName,
        id:this.addressObject.id
      }).then(res=>{
        this.$message({
          type: "success",
          message: "修改成功"
        });
        this.getList();
        this.cancelChange();
      })
    },
    cancelChange(){
      this.changeAddressDialog = false;
      this.address = [];
      this.addressText = '';
    },
    deliverGoods(){
      if(!this.waybill){
        this.$message({
          type: "error",
          message: "请输入订单号"
        });
        return
      }
      packageShipping({
        waybill:this.waybill,
        id:this.detail.id
      }).then(res=>{
        this.openDeliverGoodsOpen = false;
        this.$message({
          type: "success",
          message: "发货成功"
        });
        this.getList();
      })
    },
    updateAddress(row){
      getOrderAddress(row.id).then(res=>{
        this.addressObject = res.data;
        let province = res.data.province;
        let city = res.data.city;
        let region = res.data.region;
        let provinceCode = "";
        let cityCode = "";
        let regionCode = "";
        this.options_native_place.forEach(item=>{
          if(item.label == province) {
            provinceCode = item.value;
            item.children.forEach(child=>{
              if(child.label == city) {
                cityCode = child.value;
                child.children.forEach(c=>{
                  if(c.label == region) {
                    regionCode = c.value;
                  }
                })
              }
            })
          }
        })
        this.address = [provinceCode,cityCode,regionCode]
        this.addressText = res.data.consigneeAddress
        this.changeAddressDialog = true;
      })
    },
    handleDeliverGoods(row){
      this.detail = row
      this.waybill = ''
      this.openDeliverGoodsOpen = true;
    },
    /** 查询识别码详情列表 */
    getList() {
      this.loading = true;
      let params = Object.assign({}, this.queryParams);
      if(params.timeArr && params.timeArr.length > 0){
        params.startTime = params.timeArr[0]
        params.endTime = params.timeArr[1]
        delete params.timeArr
      }
      listActivatedList(params).then(response => {
        this.detalisList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        state: null,
        userId: null,
        creationTime: null,
        consignee: null,
        consigneePhone: null,
        consigneeAddress: null,
        region: null,
        province: null,
        city: null,
        waybill: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加识别码详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDetalis(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改识别码详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDetalis(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDetalis(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除识别码详情编号为"' + ids + '"的数据项？').then(function() {
        return delDetalis(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/codeid/activatedExport', {
        ...this.queryParams
      }, `detalis_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
